package com.smap.vector;

import java.util.List;

import com.smap.core.XY;

public class Polygon extends Geometry {

	public Polygon() {

	}

	public Polygon(List<Point> pts) {
		for (Point pt : pts) {
			this.add(pt.toXY());
		}
	}

	@Override
	public boolean contains(XY point) {

		if (this.coordinates.size() < 3) {
			return false;
		}
		if (!super.contains(point)) {
			return false;
		}
		int nvert = this.coordinates.size();
		double[] vertx = new double[nvert];
		double[] verty = new double[nvert];
		for (int i = 0; i < nvert; i++) {
			XY p = coordinates.get(i);
			vertx[i] = p.x;
			verty[i] = p.y;
		}
		return pnpoly(nvert, vertx, verty, point.x, point.y);
	}

	/**
	 * from
	 * http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by
	 * W. Randolph Franklin. what a beautiful code!
	 * 
	 * @param nvert
	 * @param vertx
	 * @param verty
	 * @param testx
	 * @param testy
	 * @return
	 */
	public static boolean pnpoly(int nvert, double[] vertx, double[] verty,
			double testx, double testy) {
		int i, j = 0;
		boolean c = false;
		for (i = 0, j = nvert - 1; i < nvert; j = i++) {
			if (((verty[i] > testy) != (verty[j] > testy))
					&& (testx < (vertx[j] - vertx[i]) * (testy - verty[i])
							/ (verty[j] - verty[i]) + vertx[i]))
				c = !c;
		}
		return c;
	}

}
